namespace Xmef.Engine
{
    using System;
    using System.Collections.Generic;
    using Xmef.Engine.Internal;
    using Xmef.Interfaces;

    [Serializable]
    public class PluginObjectManager : PluginServiceManager, IPluginObjectManager, IPluginServiceManager
    {
        public PluginObjectManager(IPluginHostManager manager)
            : base(manager)
        {
        }

        public static IPluginObjectCollection<T> GetObjectCollection<T>(IPluginHostManager manager)
        {
            if (manager != null)
            {
                Type type = typeof(T);
                PluginObjectCollection<T> collection = new PluginObjectCollection<T>();
                foreach (IPluginObject plugin in manager.ObjectManager.PluginService.GetObjects(type))
                {
                    if (plugin.IsActive)
                    {
                        IPluginObject<T> obj = plugin as IPluginObject<T>;
                        if (obj != null)
                        {
                            collection.Add(obj);
                        }
                    }
                }
                if (collection.Count > 0)
                {
                    return collection;
                }
            }
            return null;
        }

        public static IEnumerable<T> GetServiceCollection<T>(IPluginHostManager manager)
        {
            if (manager != null)
            {
                Type type = typeof(T);
                IPluginCollectionContainer host = manager;
                IPluginService<T> instance = PluginServiceManager.GetService<T>(manager.ObjectManager);
                if (instance != null)
                {
                    IList<T> collection = new List<T>();
                    foreach (T obj in instance.GetServices(type))
                    {
                        collection.Add(obj);
                    }
                    if (collection.Count > 0)
                    {
                        return collection;
                    }
                }
            }
            return null;
        }

        public bool RegisterObject(Type type, IPluginObject item)
        {
            return PluginService.Register(type, item);
        }

        public bool UnregisterObject(Type type, IPluginObject item)
        {
            return PluginService.Unregister(type, item);
        }
    }
}

